/**
 * 
 */
package com.xbang.core.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;

/**
 * 发送邮件
 * 
 * @author bocar
 * @author dev.zhang
 * 
 */
public class SendMailUtils {

	private String host;

	private String from;

	private String username;

	private String password;

	private boolean debug;

	/**
	 * @param host
	 *            the host to set
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 * @param from
	 *            the from to set
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @param debug
	 *            the debug to set
	 */
	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	/**
	 * 发送邮件
	 * 
	 * @param to
	 *            发送给谁
	 * @param toNickname
	 *            发送给谁的昵称,可以为null
	 * @param subject
	 *            标题
	 * @param messageText
	 *            邮件内容
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void send(String to, String toNickname, String subject, String messageText) throws MessagingException, UnsupportedEncodingException {
		// Step 1: Configure the mail session
		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
		props.setProperty("mail.smtp.host", host);// 指定SMTP服务器
		props.put("mail.transport.protocol", "smtp");
		Session mailSession = Session.getDefaultInstance(props);
		mailSession.setDebug(debug);// 是否在控制台显示debug信息

		// Step 2: Construct the message
		InternetAddress fromAddress = new InternetAddress(from);
		InternetAddress toAddress = null;
		if (StringUtils.isEmpty(toNickname)) {
			toAddress = new InternetAddress(to);
		} else {
			toAddress = new InternetAddress(to, toNickname);
		}

		MimeMessage testMessage = new MimeMessage(mailSession);
		testMessage.setFrom(fromAddress);
		testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
		testMessage.setSentDate(new Date());
		testMessage.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));

		testMessage.setContent(messageText, "text/html;charset=gb2312");

		// Step 3: Now send the message
		Transport transport = mailSession.getTransport("smtp");
		transport.connect(host, username, password);
		transport.sendMessage(testMessage, testMessage.getAllRecipients());
		transport.close();
	}
	/**
	 * 发送邮件
	 * @param files 
	 * 				附件列表
	 * 
	 * @param to
	 *            发送给谁
	 * @param toNickname
	 *            发送给谁的昵称,可以为null
	 * @param subject
	 *            标题
	 * @param messageText
	 *            邮件内容
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void send(String to, String toNickname, String subject, String messageText,List<File> files,String ... carbonCopys) throws MessagingException, UnsupportedEncodingException {
		// Step 1: Configure the mail session
		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
		props.setProperty("mail.smtp.host", host);// 指定SMTP服务器
		props.put("mail.transport.protocol", "smtp");
		Session mailSession = Session.getDefaultInstance(props);
		mailSession.setDebug(debug);// 是否在控制台显示debug信息

		// Step 2: Construct the message
		InternetAddress fromAddress = new InternetAddress(from);
		InternetAddress toAddress = null;
		if (StringUtils.isEmpty(toNickname)) {
			toAddress = new InternetAddress(to);
		} else {
			toAddress = new InternetAddress(to, toNickname);
		}
	//	InternetAddress [] carbonCopysAddress =new InternetAddress[carbonCopys.length];
		List<InternetAddress> carbonCopysAddress = new ArrayList<InternetAddress>();
		int i = 0;
		for (String string : carbonCopys) {
			if(StringUtils.isNotEmpty(string)){
				InternetAddress address = new InternetAddress(string);
				carbonCopysAddress.add(address);
			}
		}

		MimeMessage testMessage = new MimeMessage(mailSession);
		testMessage.setFrom(fromAddress);
		testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
		testMessage.addRecipients(javax.mail.Message.RecipientType.CC, ArrayUtils.toArray(carbonCopysAddress, InternetAddress.class));
		//testMessage.addRecipients(RecipientType., arg1);
		testMessage.setSentDate(new Date());
		testMessage.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));

		//testMessage.setContent(messageText, "text/html;charset=gb2312");
		
		
		Multipart mp = new MimeMultipart();  
        MimeBodyPart mbp = new MimeBodyPart();  
        mbp.setContent(messageText, "text/html;charset=gb2312");  
        mp.addBodyPart(mbp);    
        if(!files.isEmpty()){//有附件  
           
        	for (File file : files) {
        		 mbp=new MimeBodyPart();  
                 String filename=file.toString(); //选择出每一个附件名  
                 FileDataSource fds=new FileDataSource(filename); //得到数据源  
                 mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
                 mbp.setFileName(fds.getName());  //得到文件名同样至入BodyPart  
                 mp.addBodyPart(mbp);  
			}
        }   
		
        testMessage.setContent(mp);
		

		// Step 3: Now send the message
		Transport transport = mailSession.getTransport("smtp");
		transport.connect(host, username, password);
		transport.sendMessage(testMessage, testMessage.getAllRecipients());
		transport.close();
		
		
	}

	/**
	 * 发送邮件
	 * 
	 * @param toes
	 *            收件人
	 * @param toNicknames
	 *            收件人昵称，可以为null
	 * @param subject
	 *            标题
	 * @param messageText
	 *            邮件内容
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void send(String[] toes, String[] toNicknames, String subject, String messageText) throws MessagingException, UnsupportedEncodingException {
		// Step 1: Configure the mail session
		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
		props.setProperty("mail.smtp.host", host);// 指定SMTP服务器
		props.put("mail.transport.protocol", "smtp");
		Session mailSession = Session.getDefaultInstance(props);
		mailSession.setDebug(debug);// 是否在控制台显示debug信息

		// Step 2: Construct the message
		InternetAddress fromAddress = new InternetAddress(from);

		MimeMessage testMessage = new MimeMessage(mailSession);
		testMessage.setFrom(fromAddress);
		for (int i = 0; i < toes.length; i++) {
			InternetAddress toAddress = null;
			String to = toes[i];
			if (StringUtils.isNotEmpty(to)) {
				if (toNicknames != null && toNicknames.length > i) {
					toAddress = new InternetAddress(to, toNicknames[i]);
				} else {
					toAddress = new InternetAddress(to);
				}
				testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
			}
		}
		testMessage.setSentDate(new Date());
		testMessage.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));

		testMessage.setContent(messageText, "text/html;charset=gb2312");

		// Step 3: Now send the message
		Transport transport = mailSession.getTransport("smtp");
		transport.connect(host, username, password);
		transport.sendMessage(testMessage, testMessage.getAllRecipients());
		transport.close();
	}
}
